package action

import (
	"core/action"
	"core/corestruct"
	"core/coreutil"
	"core/myerrors"
	"fmt"
	"ht/api/htfile/data"
	"ht/api/htfile/mongo"
	"ht/api/htfile/service"
	"ht/selfreg"
	htfileservice "ht/service/htfile"

	corefile "core/file"
	"reflect"
	"strconv"
)

type UpAction struct {
}

func (p *UpAction) Do(ctx *corestruct.HttpContext) (*data.FileDto, error) {
	var c = ctx.Http
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		return nil, myerrors.NewByErr(err, "获取文件失败")
	}
	// 获取文件名，并创建新的文件存储
	if header.Size/1024/1024 > corefile.Config.MaxUpSize {
		return nil, myerrors.New(fmt.Sprintf("图片不能大于 %d M",
			corefile.Config.MaxUpSize))
	}

	var m = &mongo.File{
		Id:          coreutil.IdUtil.GetId(),
		Name:        header.Filename,
		Memo:        "",
		Size:        header.Size,
		Data:        nil,
		Gid:         coreutil.IdUtil.UuidStr(),
		FileId:      "",
		ContentType: "",
		CrtUname:    ctx.Session.Name,
	}
	m.FileId = strconv.FormatInt(m.Id, 10)

	filedata := make([]byte, header.Size)
	_, err = file.Read(filedata)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}
	r, err := service.MainService.Save(m, &filedata, ctx)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}
	return r, nil
}

func init() {
	var mact = &UpAction{}
	var maction = action.Action{
		Method: "",

		FullUrl: htfileservice.URLPrev + "/up",
		Name:    "上传" + PAGEName,
		Ename:   "",
		Memo:    "",

		PinType:    "",
		PinIslist:  false,
		PoutType:   "",
		PoutIslist: false,
		PoutIspage: false,

		AuthType: action.AuthType_Login,

		LogNeed:     false,
		LogPin:      false,
		LogPout:     false,
		LogTemplete: "",

		PrjName: "",

		Value: reflect.ValueOf(mact),
	}
	selfreg.AddAction(&maction)

}
